/*
    File name:          ProcessManagement
    File type:          Class
    Author:             Sune Krog-Meyer 09888
    Creation date:      24-03-2011
    Description:        Handles the kode written by the user.
*/
using System;
using System.Collections.Generic;
using System.Collections;
using i4pro_gruppe_d.Hardware;
using Antlr.Runtime.Tree;
using i4pro_gruppe_d.Types;
using i4pro_gruppe_d.Database;
using GalaSoft.MvvmLight.Messaging;

namespace ProcessManagement
{
    public class ProcessManagement
    {
        #region Members

        private Conveyer conveyer;
        private Gripper gripper;
        private LightSensor lightSensor;
        private Robotarm robotarm;
        private Scale scale;
        private Utility utility;
        private const string CRLF = "\r\n";
        private const string defaultVector = "defVector";
        private int pointCount;
        private Brick currentBrick = new Brick();
        private AbstractDatabase myDatabase = AbstractDatabase.Instance;
        private Robot robot;
        private Vector vector;
        private Hashtable variableIntHT = new Hashtable();
        private Hashtable variableVectorHT = new Hashtable();
        private bool hvisFlag = true;
        private int pointCountMoveTo;
        private List<Vector> VectorList;

        private class IntMappedValue
        {
            public int value { get; set; }
            public string type { get; set; }
        }
        private class VectorMappedValue
        {
            public List<int> value { get; set; }
            public string type { get; set; }
        }
        public class variableException : Exception
        {
            public variableException(string msg)
                : base(msg)
            {
            }
        }

    	private bool robotConnected = true;
        #endregion
       
        #region Construction
        public ProcessManagement()
        {
            conveyer = new Conveyer(robotConnected);
			gripper = new Gripper(robotConnected);
			lightSensor = new LightSensor(robotConnected);
			robotarm = new Robotarm(robotConnected);
			scale = new Scale(robotConnected);
            utility = new Utility(robotConnected);
            robot = new Robot();
            vector = new Vector() { x = 169000, y = 0, z = 500000, pitch = -630000, roll = 0};
            List<Vector> VectorList = new List<Vector>();

            pointCount = 1;
            pointCountMoveTo = 1;
        }

        public ProcessManagement(bool _robotConnected)
        {
            robotConnected = _robotConnected;
            conveyer = new Conveyer(robotConnected);
            gripper = new Gripper(robotConnected);
            lightSensor = new LightSensor(robotConnected);
            robotarm = new Robotarm(robotConnected);
            scale = new Scale(robotConnected);
            utility = new Utility(robotConnected);
            robot = new Robot();
            vector = new Vector() { x = 169000, y = 0, z = 500000, pitch = -630000, roll = 0 };
            List<Vector> VectorList = new List<Vector>();

            pointCount = 1;
        }
        #endregion

        #region Properties
        
        public Robotarm Robotarm
        {
            get { return robotarm; }
            set { robotarm = value; }
        }

        public Utility Utility
        {
            get { return utility; }
            set { utility = value; }
        }

        public AbstractDatabase MyDatabase
        {
            get { return myDatabase; }
            set { myDatabase = value; }
        }

        public bool RobotConnected { get; set; }

        #endregion

        #region Commands
        
        /// <summary>
        /// Creates static coordinates for the robot to move to.
        /// These coordinates can called by the robot while running.
        /// </summary>
        /// <returns> A list with all the static coordinates </returns>
        public List<Vector> CreatePoints()
        {
            List<Vector> VectorList = new List<Vector>();


            //vector 1
            Vector RelMoveUpVector = new Vector
            {
                x = 0,
                y = 0,
                z = 65000,
                pitch = 0,
                roll = 0,
                type = -32767,
                pointNumber = pointCount++
            };
            VectorList.Add(RelMoveUpVector);


            //vector 2
            Vector RelMoveDownVector = new Vector
            {
                x = 0,
                y = 0,
                z = -65000,
                pitch = 0,
                roll = 0,
                type = -32767,
                pointNumber = pointCount++
            };
            VectorList.Add(RelMoveDownVector);

            //vector 3
            Vector RelPitchUpVector = new Vector
            {
                x = 0,
                y = 0,
                z = 0,
                pitch = -90000,
                roll = 0,
                type = -32767,
                pointNumber = pointCount++
            };
            VectorList.Add(RelPitchUpVector);

            //vector 4
            Vector RelPitchDownVector = new Vector
            {
                x = 0,
                y = 0,
                z = 0,
                pitch = 90000,
                roll = 0,
                type = -32767,
                pointNumber = pointCount++
            };
            VectorList.Add(RelPitchDownVector);

            //vector 5
            Vector RelRollRightVector = new Vector
            {
                x = 0,
                y = 0,
                z = 0,
                pitch = 0,
                roll = 90000,
                type = -32767,
                pointNumber = pointCount++
            };
            VectorList.Add(RelRollRightVector);

            //vector 6
            Vector RelRollLeftVector = new Vector
            {
                x = 0,
                y = 0,
                z = 0,
                pitch = 0,
                roll = -90000,
                type = -32767,
                pointNumber = pointCount++
            };
            VectorList.Add(RelRollLeftVector);

            //vector 7
            Vector aboveConveyerVector = new Vector
            {
                x = 257920,
                y = 49710,
                z = 168530,
                pitch = -90000,
                roll = 14000,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(aboveConveyerVector);


            //vector 8
            Vector aboveWeightVector = new Vector
            {
                x = 11400,
                y = 397540,
                z = 136000,
                pitch = -90000,
                roll = 183050,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(aboveWeightVector);

            //vector 9
            Vector WaypointSortVector = new Vector
            {
                x = 322030,
                y = -160210,
                z = 243180,
                pitch = -90000,
                roll = 0,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(WaypointSortVector);

            //vector 10
            Vector BlueSortVector = new Vector
            {
                x = -192850,
                y = -247260,
                z = 163140,
                pitch = -90000,
                roll = -37490,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(BlueSortVector);

            //vector 11
            Vector WhiteSortVector = new Vector
            {
                x = -117250,
                y = -249370,
                z = 161280,
                pitch = -90000,
                roll = -22470,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(WhiteSortVector);

            //vector 12
            Vector RedSortVector = new Vector
            {
                x = -29960,
                y = -274100,
                z = 161200,
                pitch = -90000,
                roll = -4200,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(RedSortVector);

            //vector 13
            Vector YellowSortVector = new Vector
            {
                x = 46450,
                y = -271790,
                z = 161200,
                pitch = -90000,
                roll = 10720,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(YellowSortVector);

            //vector 14
            Vector GreenSortVector = new Vector
            {
                x = 123940,
                y = -274950,
                z = 157460,
                pitch = -90000,
                roll = 27020,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(GreenSortVector);

            //vector 15
            Vector UnknownSortVector = new Vector
            {
                x = 259960,
                y = -354490,
                z = 171860,
                pitch = -90000,
                roll = 37810,
                type = -32766,
                pointNumber = pointCount++
            };
            VectorList.Add(UnknownSortVector);

            //vector 16
            Vector RelMoveUpPitchVector = new Vector
            {
                x = 0,
                y = 0,
                z = 50000,
                pitch = 0,
                roll = 0,
                type = -32767,
                pointNumber = pointCount++
            };
            VectorList.Add(RelMoveUpPitchVector);


            //vector 17
            Vector RelMoveDownPitchVector = new Vector
            {
                x = 0,
                y = 0,
                z = -50000,
                pitch = 0,
                roll = 0,
                type = -32767,
                pointNumber = pointCount++
            };
            VectorList.Add(RelMoveDownPitchVector);


            return VectorList;
        }

        /// <summary>
        /// A helpfunktion to make the program run smoother. 
        /// Sometimes it needs some delays to avoid skipping funktioncalls, due to the controllerbox
        /// </summary>
		public void sleep()
        {
            System.Threading.Thread.Sleep(500);
        }
        #endregion

        /// <summary>
        /// This function dose a recursive run through of a tree
        /// and calls the function StatementSwitch to execute the commands in the script.
        /// </summary>
        /// <param name="tree">CommonTree to be worked no</param>
        public void DFSRecursiveRunThroughOfAST(CommonTree tree)
        {
            try
            {

                if (tree.Children != null)
                {
                    foreach (var child in tree.Children)
                    {
                        if(utility.IsEmergency())
                        {
                            //Write emergency event to database
                            EventLog myEvent = new EventLog();
                            myEvent.LogEntry = myEvent.GetLogDescription((int)DescriptionType.Emergency);
                            myEvent.LogTime = DateTime.Now;
                            myEvent.LogType = (int) Codes.Emergency;
                            myDatabase.WriteEventLog(myEvent);
                        }
                        else
                        {
                            var childTree = child as CommonTree;

                            if (childTree.Text != CRLF)
                            {
                                StatementSwitch(tree, childTree);

                                if(!(childTree.Text == "mens"||
                                   childTree.Text == "hvis" ||
                                   childTree.Text == "loop" ||
                                   childTree.Text == "ellershvis" ||
                                   childTree.Text == "ellers"))
                                DFSRecursiveRunThroughOfAST(childTree);
                            }                            
                        }
                    }
                }
            }
            catch (NullReferenceException)
            {
            }
        }
        /// <summary>
        /// This function dose a recursive run through of a tree
        /// to find errors concerning variable declaretion and usage.   
        /// </summary>
        /// <param name="tree">CommonTree to be worked no</param>
        public void DFSRecursiveRunThroughOfASTForDebug(CommonTree tree)
        {
            try
            {

                if (tree.Children != null)
                {
                    foreach (var child in tree.Children)
                    {
                        if (utility.IsEmergency())
                        {
                            //Write emergency event to database
                            EventLog myEvent = new EventLog();
                            myEvent.LogEntry = myEvent.GetLogDescription((int)DescriptionType.Emergency);
                            myEvent.LogTime = DateTime.Now;
                            myEvent.LogType = (int)Codes.Emergency;
                            myDatabase.WriteEventLog(myEvent);
                        }
                        else
                        {
                            var childTree = child as CommonTree;

                            if (childTree.Text != CRLF)
                            {
                                DebugSwitch(childTree);

                                DFSRecursiveRunThroughOfASTForDebug(childTree);
                            }
                        }
                    }
                }
            }
            catch (NullReferenceException)
            {
            }
        }

        /// <summary>
        /// Prints out a CommonTree in the console
        /// </summary>
        /// <param name="tree">CommonTree to be worked no</param>
        /// <param name="indent">Indicator for what branch of the tree the child is on</param>
        static void Print(CommonTree tree, string indent)
        {
            Console.WriteLine(indent + tree.ToString());

            if (tree.Children != null)
            {
                indent += "\t";

                foreach (var child in tree.Children)
                {
                    var childTree = child as CommonTree;

                    //if (childTree.Text != "\r\n")
                    Print(childTree, indent);
                }
            }
        }

        /// <summary>
        /// This function executes the commands in the CommonTree childTree
        /// </summary>
        /// <param name="tree">CommonTree to be worked no</param>
        /// <param name="childTree">Child tree of the first parameter</param>
    	private void StatementSwitch(CommonTree tree, CommonTree childTree)
    	{
    	    Messenger messenger = Messenger.Default;
    		switch (childTree.Text)
    		{
                
                case "startConveyer":
    			{
                    //Sends message to the system that the conveyer is starting
                    messenger.Send("Starting Conveyer", "ExecutingCommand");

                    //starts the conveyer
                    conveyer.Start();
                    sleep();
                    //waiting for movement to finish
                    while (!conveyer.CheckMotionStatus())
                    {                      
                    }

                    //reenables some motionchecks, which is disable when the lightsensor is activated. 
                    //The lightsensor is needed for making the conveyer to stop again
                    robotarm.WatchMotion(true, true);

                    break;
    			}
    			case "stopConveyer":
    			{
                    messenger.Send("Stopping Conveyer", "ExecutingCommand");
                    //Stop the conveyer
                    conveyer.Stop();
    				break;
    			}
    			case "home":
    		    {
                    messenger.Send(true, "Homing");
                    messenger.Send("Homing Robot", "ExecutingCommand");
                    
                    //Positions for the log
                    robot.PositionBefore = new[] { 0, 0, 0, 0, 0 };
                    robot.GripSpanBefore = 0;
                    
                    //Homing the robot, to find its start coordinates
                    utility.HomeRobot();

                    sleep();
                  
                    //Positions for the log
                    robot.PositionAfter = new [] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
    				robot.GripSpanAfter = gripper.MeasureWidth();
                                                        
                    //Sending positions to the log
                    myDatabase.WriteRobot(robot);

                    messenger.Send(false, "Homing");
                                    
    				break;
    			}
    			case "init":
    			{
                    messenger.Send("Initializing Robot", "ExecutingCommand");

                    //prints the tree. This is for debug only
                    Print(tree, " ");

                    //Initializations for the robot to work
    				utility.InitRobot();
    				utility.SetControl('&', true);

                    //Creating new vector, which can contain coordinates
    				utility.DefineVector('A', defaultVector, 100);

                    //Getting all the static coordinates
    				VectorList = CreatePoints();

    				foreach (Vector vector in VectorList)
    				{
                        //Adding the coordinates retrieved, to the robotvector, defined above
    					utility.AddCoordinatePoint(defaultVector, vector);
    				}
                    
                    //Enables motionchecks (check when a movement stats and stops)
    				robotarm.WatchMotion(true, true);

                    //Write start event to database
                    EventLog myEvent = new EventLog();
                    myEvent.LogEntry = myEvent.GetLogDescription((int)DescriptionType.RobotStarted);
                    myEvent.LogTime = DateTime.Now;
                    myEvent.LogType = (int)Codes.Command;
                    myDatabase.WriteEventLog(myEvent);

    				break;
    			}
    			case "mtWeight":
    			{
                    messenger.Send("Using Weight", "ExecutingCommand");
    				                    
                    //Posistions for the log
                    robot.GripSpanBefore = gripper.MeasureWidth();
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };

                    //Moves the robot to the 8th coordinate in the defaultvector
    				robotarm.MoveTo(defaultVector, 8);
    				sleep();
                    //waiting for movement to finish
    				while (!robotarm.CheckMotionStatus())
    				{
    				}

                    //Positions for the log
                    vector = VectorList[7];
    				robot.GripSpanAfter = gripper.MeasureWidth();
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    myDatabase.WriteRobot(robot);

    				break;
    			}
    			case "mtConveyer":
    			{
                    messenger.Send("Moving to conveyer", "ExecutingCommand");

                    //Positions for the log
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanBefore = gripper.MeasureWidth();

                    //Moves the robot to the 7th coordinate in the defaultvector
                    robotarm.MoveTo(defaultVector, 7);
    				sleep();
                    //waiting for movement to finish
    				while (!robotarm.CheckMotionStatus())
    				{
    				}

                    //Positions for the log
                    vector = VectorList[6];
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanAfter = gripper.MeasureWidth();
                    myDatabase.WriteRobot(robot);

    				break;
    			}
    			case "mtSortbox":
    			{
                    messenger.Send("Moving to sortbox", "ExecutingCommand");
                    //Positions for the log
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanBefore = gripper.MeasureWidth();

                    //Moves the robot to the 9th coordinate in the defaultvector
                    robotarm.MoveTo(defaultVector, 9);
                    sleep();
                    //waiting for movement to finish
                    while (!robotarm.CheckMotionStatus())
                    {
                    }

                    //Calling the MtSortBox help funktion
                    MtSortBox();
    				sleep();
                    //waiting for movement to finish
                    while (!robotarm.CheckMotionStatus())
    				{
    				}

                    //Calling the ReleaseBrick help funktion
                    ReleaseBrick();

                    //Moves the robot to the 9th coordinate in the defaultvector
                    robotarm.MoveTo(defaultVector, 9);
                    sleep();
                    //waiting for movement to finish
                    while (!robotarm.CheckMotionStatus())
                    {
                    }

                    //Positions for the log
                    vector = VectorList[8];
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanAfter = gripper.MeasureWidth();
                    myDatabase.WriteRobot(robot);

    				//Add brick to database and errase curretBrick
    				if (currentBrick.BrickType != -1)
    					myDatabase.WriteBrick(currentBrick);
    				else
    				{
    					EventLog myEvent = new EventLog();
    					myEvent.LogEntry = myEvent.GetLogDescription((int)DescriptionType.BrickFailed);
    					myEvent.LogTime = DateTime.Now;
    					myEvent.LogType = (int)Codes.Error;
    					myDatabase.WriteEventLog(myEvent);
    				}

                    //Resets the current brick's data
    				currentBrick = new Brick();
    				break;
    			}
    			case "grapBrick":
    			{
                    messenger.Send("Grapping brick", "ExecutingCommand");

                    //Checks if a new brick has been grapped
                    if (currentBrick.Time == new DateTime())
                    {
                        currentBrick.Time = DateTime.Now;
                        messenger.Send(true, "Newbricknotice");
                    }

                    //Positions for the log
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanBefore = gripper.MeasureWidth();

                    //Calling the GrapBrick help funktion
                    GrapBrick();

                    //Positions for the log
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanAfter = gripper.MeasureWidth();
                    myDatabase.WriteRobot(robot);

    				break;
    			}
    			case "releaseBrick":
    		    {
                    messenger.Send("Releasing brick", "ExecutingCommand");

                    //Positions for the log
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanBefore = gripper.MeasureWidth();

                    //Calling the ReleaseBrick help funktion
                    ReleaseBrick();

                    //Positions for the log
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanAfter = gripper.MeasureWidth();
                    myDatabase.WriteRobot(robot);

                    break;
    			} 
                case "measureBrick":
    		    {
                    messenger.Send("Measuring Brick", "ExecutingCommand");

                    //Checks which side is currently measured
                    if (currentBrick.Width == 0)
                    {
                        //Measure the brick and save the data
                        currentBrick.Width = gripper.MeasureWidth();
                        messenger.Send(currentBrick.Width, "Width");
                    }
                    else if (currentBrick.Height == 0)
                    {
                        //Measure the brick and save the data
                        currentBrick.Height = gripper.MeasureWidth();
                        messenger.Send(currentBrick.Height, "Height");
                    }
                    else if (currentBrick.Length == 0)
                    {
                        //Measure the brick and save the data
                        currentBrick.Length = gripper.MeasureWidth();
                        messenger.Send(currentBrick.Length, "Length");
                    }
                    else
                        Console.WriteLine("All sides was already measured");

    		        break;
    		    }
    			case "weighBrick":
    			{
                    messenger.Send("Weighing brick", "ExecutingCommand");
                    
                    //Weighing the brick and saving the data
                    currentBrick.Weight = scale.MeasureWeight();
                    Console.WriteLine("Weight: " + currentBrick.Weight);
                    messenger.Send(currentBrick.Weight, "Weight");
    				break;
    			}
    			case "rollGrapperLeft":
    			{
                    messenger.Send("Rolling grapper left", "ExecutingCommand");
                    //Positions for the log
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanBefore = gripper.MeasureWidth();

                    //Moves the robot to the 6th position in the defaultvector
                    robotarm.MoveTo(defaultVector, 6);
    				sleep();
                    //Waiting for movement to end
                    while (!robotarm.CheckMotionStatus())
    				{
    					sleep();
    				}

                    //Positions for the log
                    vector.roll -= 90000;
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanAfter = gripper.MeasureWidth();
                    myDatabase.WriteRobot(robot);
                    
                    break;
    			}
    			case "rollGrapperRight":
    			{
                    messenger.Send("Rolling grapper right", "ExecutingCommand");

                    //Positions for the log
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanBefore = gripper.MeasureWidth();

                    //Moves the robot to the 5th position in the defaultvector
                    robotarm.MoveTo(defaultVector, 5);
    				sleep();
                    //Waiting for movement to end
                    while (!robotarm.CheckMotionStatus())
    				{
    					sleep();
    				}

                    //Positions for the log
                    vector.roll += 90000;
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanAfter = gripper.MeasureWidth();
                    myDatabase.WriteRobot(robot);

    				break;
    			}
    			case "pitchGrapperUp":
    			{
                    messenger.Send("Pitching grapper up", "ExecutingCommand");

                    //Positions for the log
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanBefore = gripper.MeasureWidth();

                    //Moves the robot to the 4th position in the defaultvector
                    robotarm.MoveTo(defaultVector, 4);
    				sleep();
                    //Waiting for movement to end
                    while (!robotarm.CheckMotionStatus())
    				{
    					sleep();
    				}

                    //Positions for the log
                    vector.pitch += 90000;
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanAfter = gripper.MeasureWidth();
                    myDatabase.WriteRobot(robot);

    				break;
    			}
    			case "pitchGrapperDown":
    			{
                    messenger.Send("Pitching grapper down", "ExecutingCommand");

                    //Positions for the log
                    robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanBefore = gripper.MeasureWidth();

                    //Moves the robot to the 3th position in the defaultvector
                    robotarm.MoveTo(defaultVector, 3);
    				sleep();
                    //Waiting for movement to end
                    while (!robotarm.CheckMotionStatus())
    				{
    					sleep();
    				}

                    //Positions for the log
                    vector.pitch -= 90000;
                    robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                    robot.GripSpanAfter = gripper.MeasureWidth();
                    myDatabase.WriteRobot(robot);

    				break;
    			}
    			case "hvis":
    		    {
    		        hvisFlag = true;
                    if (tree.Children != null)
    				{
                        var tempChildTree = childTree.Children[0] as CommonTree;

    					if (tempChildTree.Text != CRLF)
    						if(ValidateExpression(tempChildTree))
    				        {
                                CommonTree temp = new CommonTree();
                                for (int i = 1; i < childTree.ChildCount; i++)
                                {
                                    temp.AddChild(childTree.Children[i] as CommonTree);
                                }
    				            hvisFlag = false;
                                DFSRecursiveRunThroughOfAST(temp);
    				        }
                            
    				}
    				break;
    			}
                case "ellershvis":
    		    {
                    if (tree.Children != null)
                    {
                        var tempChildTree = childTree.Children[0] as CommonTree;

                        if (tempChildTree.Text != CRLF)
                            if (ValidateExpression(tempChildTree))
                            {
                                CommonTree temp = new CommonTree();
                                for (int i = 1; i < childTree.ChildCount; i++)
                                {
                                    temp.AddChild(childTree.Children[i] as CommonTree);
                                }
                                hvisFlag = false;
                                DFSRecursiveRunThroughOfAST(temp);
                            }
                    }
                    break;
    		    }
                case "ellers":
    		    {
    		        if(hvisFlag)
    		        {
                        CommonTree temp = new CommonTree();
                        for (int i = 0; i < childTree.ChildCount; i++)
                        {
                            temp.AddChild(childTree.Children[i] as CommonTree);
                        }
                        
    		            DFSRecursiveRunThroughOfAST(temp);
    		        }

                    break;
    		    }
                case "var":
    		    {
    		        variableDeclaretion(childTree.Children[0].ToString(), childTree.Children[1].ToString());
                    break;
                }
                case "=":
                {
                    int result = mathExpression(childTree.Children[1] as CommonTree);
                    variableAssignment(childTree.Children[0].ToString(), result);
                    break;
                }
                case "+=":
                {
                    int result = mathExpression(childTree.Children[1] as CommonTree);
                    variableAssignmentPlus(childTree.Children[0].ToString(), result);
                    break;
                }
                case "-=":
                {
                    int result = mathExpression(childTree.Children[1] as CommonTree);
                    variableAssignmentMinus(childTree.Children[0].ToString(), result);
                    break;
                }
                case "++":
                {
                    variablePlusPlus(childTree.Children[0].ToString());
                    break;
                }
                case "--":
                {
                    variableMinusMinus(childTree.Children[0].ToString());
                    break;
                }
                case "assignVector":
    		    {
                    if (variableVectorHT.ContainsKey(childTree.Children[0].ToString()))
                    {
                        IDictionaryEnumerator myEnumerator = variableVectorHT.GetEnumerator();
                        List<int> value = new List<int>();
                        value.Add(childValueInt(childTree.Children[1] as CommonTree));
                        value.Add(childValueInt(childTree.Children[2] as CommonTree));
                        value.Add(childValueInt(childTree.Children[3] as CommonTree));
                        value.Add(childValueInt(childTree.Children[4] as CommonTree));
                        value.Add(childValueInt(childTree.Children[5] as CommonTree));

                        while (myEnumerator.MoveNext())
                        {
                            if (myEnumerator.Key.ToString() == childTree.Children[0].ToString())
                            {
                                var temp = myEnumerator.Value as VectorMappedValue;
                                temp.value = value;

                                variableVectorHT.Remove(childTree.Children[0].ToString());
                                variableVectorHT.Add(childTree.Children[0].ToString(), temp);
                                return;
                            }
                        }

                    }
                    else
                    {
                        throw new variableException("Variable (vector) " + childTree.Children[0].ToString() + " is not declared");
                    }
                    break;
    		    }
                case "moveTo":
    		    {
    		        List<int> list = new List<int>();
                    list = childValueVector(childTree);
                    Vector v = new Vector();
                    v.x = list[0];
                    v.y = list[1];
                    v.z = list[2];
                    v.pitch = list[3];
                    v.roll = list[4];
    		        v.type = -32767;
    		        v.pointNumber = pointCountMoveTo;
                    messenger.Send("Moving to (" + v.x + ", " + v.y + ", " + v.z + ")", "ExecutingCommand");
                    
                    robot.PositionBefore = new[] {vector.x, vector.y, vector.z, vector.pitch, vector.roll};
    		        robot.GripSpanBefore = gripper.MeasureWidth();

                    utility.AddCoordinatePoint("moveToVector", v);

                    robotarm.MoveTo("moveToVector", (short) pointCountMoveTo);
    		        pointCountMoveTo++;
    		        
                    sleep();
                    while (!robotarm.CheckMotionStatus())
                    {}

    		        robot.PositionAfter = new[] {vector.x, vector.y, vector.z, vector.pitch, vector.roll};
    		        robot.GripSpanAfter = gripper.MeasureWidth();
    		        myDatabase.WriteRobot(robot);
                    break;
    		    }
                case "loop":
    		    {
    		        int a;
                    if (int.TryParse(childTree.Children[0].ToString(), out a))
                    {
                        int loopCount = 0;
                        CommonTree temp =  new CommonTree();
                        for (int i = 1; i < childTree.ChildCount; i++ )
                        {
                            temp.AddChild(childTree.Children[i] as CommonTree);
                        }

                            while (loopCount < a)
                            {
                                DFSRecursiveRunThroughOfAST(temp);

                                loopCount++;
                            }
                    }
                    break;
    		    }
                case "mens":
    		    {
    		        
                    if (tree.Children != null)
    				{
    					var tempChildTree = childTree.Children[0] as CommonTree;

    					if (tempChildTree.Text != CRLF)
    						while(ValidateExpression(tempChildTree))
    				        {
                                CommonTree temp = new CommonTree();
                                for (int i = 1; i < childTree.ChildCount; i++)
                                {
                                    temp.AddChild(childTree.Children[i] as CommonTree);
                                }

                                DFSRecursiveRunThroughOfAST(temp);
    				        }
                                        
    				}
    		        break;
                    
    		    }
				default:
    			{
    				break;
    			}
    		}
    	}

        /// <summary>
        /// This function contains the functionalities that use variables
        /// and is used for debugging of variables in the script.
        /// </summary>
        /// <param name="childTree">CommonTree to be worked on</param>
  	    private void DebugSwitch(CommonTree childTree)
    	{
    	    Messenger messenger = Messenger.Default;
    		switch (childTree.Text)
    		{
                case "var":
                    {
                        variableDeclaretion(childTree.Children[0].ToString(), childTree.Children[1].ToString());
                        break;
                    }
                case "=":
                    {
                        int result = mathExpression(childTree.Children[1] as CommonTree);
                        variableAssignment(childTree.Children[0].ToString(), result);
                        break;
                    }
                case "+=":
                    {
                        int result = mathExpression(childTree.Children[1] as CommonTree);
                        variableAssignmentPlus(childTree.Children[0].ToString(), result);
                        break;
                    }
                case "-=":
                    {
                        int result = mathExpression(childTree.Children[1] as CommonTree);
                        variableAssignmentMinus(childTree.Children[0].ToString(), result);
                        break;
                    }
                case "++":
                    {
                        variablePlusPlus(childTree.Children[0].ToString());
                        break;
                    }
                case "--":
                    {
                        variableMinusMinus(childTree.Children[0].ToString());
                        break;
                    }
                case "assignVector":
                    {
                        if (variableVectorHT.ContainsKey(childTree.Children[0].ToString()))
                        {
                            IDictionaryEnumerator myEnumerator = variableVectorHT.GetEnumerator();
                            List<int> value = new List<int>();
                            value.Add(childValueInt(childTree.Children[1] as CommonTree));
                            value.Add(childValueInt(childTree.Children[2] as CommonTree));
                            value.Add(childValueInt(childTree.Children[3] as CommonTree));
                            value.Add(childValueInt(childTree.Children[4] as CommonTree));
                            value.Add(childValueInt(childTree.Children[5] as CommonTree));

                            while (myEnumerator.MoveNext())
                            {
                                if (myEnumerator.Key.ToString() == childTree.Children[0].ToString())
                                {
                                    var temp = myEnumerator.Value as VectorMappedValue;
                                    temp.value = value;

                                    variableVectorHT.Remove(childTree.Children[0].ToString());
                                    variableVectorHT.Add(childTree.Children[0].ToString(), temp);
                                    return;
                                }
                            }

                        }
                        else
                        {
                            throw new variableException("Variable (vector) " + childTree.Children[0].ToString() + " is not declared");
                        }
                        break;
                    }
                case "moveTo":
                    {
                        List<int> list = new List<int>();
                        list = childValueVector(childTree);
                        Vector v = new Vector();
                        v.x = list[0];
                        v.y = list[1];
                        v.z = list[2];
                        v.pitch = list[3];
                        v.roll = list[4];
                        v.type = -32767;
                        v.pointNumber = pointCountMoveTo;
                        messenger.Send("Moving to (" + v.x + ", " + v.y + ", " + v.z + ")", "ExecutingCommand");

                        robot.PositionBefore = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                        robot.GripSpanBefore = gripper.MeasureWidth();

                        utility.AddCoordinatePoint("moveToVector", v);

                        robotarm.MoveTo("moveToVector", (short)pointCountMoveTo);
                        pointCountMoveTo++;

                        sleep();
                        while (!robotarm.CheckMotionStatus())
                        { }

                        robot.PositionAfter = new[] { vector.x, vector.y, vector.z, vector.pitch, vector.roll };
                        robot.GripSpanAfter = gripper.MeasureWidth();
                        myDatabase.WriteRobot(robot);
                        break;
                    }
				default:
    			    {
    				    break;
    			    }
    		}
    	}

        /// <summary>
        /// This function validate whether or not the expression in the CommonTree is true or false
        /// </summary>
        /// <param name="tempChildTree">CommonTree containing a expression</param>
        /// <returns>Returns true if the expression is true else returns false</returns>
    	private bool ValidateExpression(CommonTree tempChildTree)
    	{
    		switch (tempChildTree.Text)
    		{
    			case "==":
    			{
    			    int a = childValueInt(tempChildTree.Children[0] as CommonTree);
                    int b = childValueInt(tempChildTree.Children[1] as CommonTree);
                    
    				if (a == b)
    				{
    				    return true;

    				}

    			    return false;
    			}
    			case "!=":
    			{
                    int a = childValueInt(tempChildTree.Children[0] as CommonTree);
                    int b = childValueInt(tempChildTree.Children[1] as CommonTree);
 
    				if (a != b)
    				{
                        return true;

                    }

                    return false;
    			}
    			case ">=":
    			{
                    int a = childValueInt(tempChildTree.Children[0] as CommonTree);
                    int b = childValueInt(tempChildTree.Children[1] as CommonTree);
 
    				if (a >= b)
    				{
                        return true;

                    }

                    return false;
    			}
    			case "<=":
    			{
                    int a = childValueInt(tempChildTree.Children[0] as CommonTree);
                    int b = childValueInt(tempChildTree.Children[1] as CommonTree);
 
    				if (a <= b)
    				{
                        return true;

                    }

                    return false;
    			}
    			case "<":
    			{
                    int a = childValueInt(tempChildTree.Children[0] as CommonTree);
                    int b = childValueInt(tempChildTree.Children[1] as CommonTree);
 
    				if (a < b)
    				{
    				    return true;
    				}
    			    
                    return false;
    			}
    			case ">":
    			{
                    int a = childValueInt(tempChildTree.Children[0] as CommonTree);
                    int b = childValueInt(tempChildTree.Children[1] as CommonTree);
 
    				if (a > b)
    				{
                        return true;
                    }

                    return false;
    			}
    		}

    	    return false;
    	}

        /// <summary>
        /// Moves the robotarm and current brick to a sortingpoint dependend of which bricktype it is
        /// </summary>
        private void MtSortBox() 
		{
            //Checks the bricktype and moves according to the type
    		switch(currentBrick.BrickType)
    		{
    			case 1:
    			{
                    Console.WriteLine("Blue Brick Found with dens: " + currentBrick.Density);
    				//Moves to the 10th vector in the defaultvector
                    robotarm.MoveTo(defaultVector, 10);
    				break;
    			}
    			case 2:
    			{
                    Console.WriteLine("White Brick Found with dens: " + currentBrick.Density);
                    //Moves to the 11th vector in the defaultvector
                    robotarm.MoveTo(defaultVector, 11);
    				break;
    			}
    			case 3:
    			{
                    Console.WriteLine("Red Brick Found with dens: " + currentBrick.Density);
                    //Moves to the 12th vector in the defaultvector
                    robotarm.MoveTo(defaultVector, 12);
    				break;
    			}
    			case 4:
    			{
                    Console.WriteLine("Yellow Brick Found with dens: " + currentBrick.Density);
                    //Moves to the 13th vector in the defaultvector
                    robotarm.MoveTo(defaultVector, 13);
    				break;
    			}
    			case 5:
    			{
                    Console.WriteLine("Green Brick Found with dens: " + currentBrick.Density);
                    //Moves to the 14th vector in the defaultvector
                    robotarm.MoveTo(defaultVector, 14);
    				break;
    			}
                default:
                {
                    Console.WriteLine("Unknown Brick Found with dens: " + currentBrick.Density);
                    //Moves to the 15th vector in the defaultvector
                    robotarm.MoveTo(defaultVector, 15);
                    break;
                }
    		}
    	}

        /// <summary>
        /// Releasese the brick and moves back to the starting position
        /// </summary>
        private void ReleaseBrick() 
        {
            //Checks if the robotarm has been pitched up
            if (vector.pitch == -90000)
                //Moves to the 2nd vector in the defaultvector
                robotarm.MoveTo(defaultVector, 2);
            else
                //Moves to the 17th vector in the defaultvector
                robotarm.MoveTo(defaultVector, 17);

            sleep();
            //Waiting for movement to end
    		while (!robotarm.CheckMotionStatus())
    		{
    		}
    		sleep();

            //Opens the gripper
            gripper.Open();
    		sleep();
            //Waiting for movement to end
            while (!robotarm.CheckMotionStatus())
    		{
    		}
            sleep();

            //Checks if the gripper is pitched up
            if (vector.pitch == -90000)
                //Moves to the 1st vector in the defaultvector
                robotarm.MoveTo(defaultVector, 1);
            else
                //Moves to the 16th vector in the defaultvector
                robotarm.MoveTo(defaultVector, 16);

            sleep();
            //Waiting for movement to end
            while (!robotarm.CheckMotionStatus())
    		{
    		}
            sleep();

            //Closes the gripper
            gripper.Close();
    		sleep();
            //Waiting for movement to end
            while (!robotarm.CheckMotionStatus())
    		{
    		}
            sleep();
        }

        private void GrapBrick()
        {
            //Opens the gripper
            gripper.Open();
            sleep();
            //Waiting for movement to end
            while (!robotarm.CheckMotionStatus())
            {
            }
            sleep();

            //Checks if the gripper is pitched up
            if (vector.pitch == -90000)
                //Moves to the 2nd vector in the defaultvector
                robotarm.MoveTo(defaultVector, 2);
            else
                //Moves to the 17th vector in the defaultvector
                robotarm.MoveTo(defaultVector, 17);
            
            sleep();
            //Waiting for movement to end
            while (!robotarm.CheckMotionStatus())
            {
            }
            sleep();

            //Closes the gripper
            gripper.Close();
            sleep();
            //Waiting for movement to end
            while (!robotarm.CheckMotionStatus())
            {
            }
            sleep();

            //Checks if the gripper is pitched up
            if (vector.pitch == -90000)
                //Moves to the 1st vector in the defaultvector
                robotarm.MoveTo(defaultVector, 1);
            else
                //Moves to the 16th vector in the defaultvector
                robotarm.MoveTo(defaultVector, 16);
            
            sleep();
            //Waiting for movement to end
            while (!robotarm.CheckMotionStatus())
            {
            }
            sleep();
        }

        /// <summary>
        /// Declares a variable and assignes it a type.
        /// Throwes exception if the variable is already declared
        /// Throwes exception if type is not supported
        /// </summary>
        /// <param name="name">The name of the variable to be declared</param>
        /// <param name="type">The type of the variable to be declared, integer or vector</param>
        private void variableDeclaretion(string name, string type)
        {

            if (variableIntHT.ContainsKey(name) || variableVectorHT.ContainsKey(name))
            {
                throw new variableException("Variable " + name + " already declared");
            }
            else if(type == "integer")
            {
                IntMappedValue temp = new IntMappedValue();
                temp.type = type;
                variableIntHT.Add(name, temp);
            }
            else if (type == "vector")
            {
                VectorMappedValue temp = new VectorMappedValue();
                temp.type = type;
                variableVectorHT.Add(name, temp);
            }
            else
            {
                throw new variableException("Variable type not supported");
            }

        }

        /// <summary>
        /// Assigns a value to a variable of the type integer
        /// Throws exception if the variable is not declared
        /// </summary>
        /// <param name="name">The name of the variable of the type integer to be worked on</param>
        /// <param name="value">The value that the variable will be assigned</param>
        private void variableAssignment(string name, int value)
        {
            if (variableIntHT.ContainsKey(name))
            {
                IDictionaryEnumerator myEnumerator = variableIntHT.GetEnumerator();

                while (myEnumerator.MoveNext())
                {
                    if (myEnumerator.Key.ToString() == name)
                    {
                        var temp = myEnumerator.Value as IntMappedValue;
                        temp.value = value;

                        variableIntHT.Remove(name);
                        variableIntHT.Add(name, temp);
                        return;
                    }
                }

            }
            else
            {
                throw new variableException("Variable (integer) " + name + " is not declared");
            }
        }


        /// <summary>
        /// Adds the value of the variable to the parameter value and assigns it to the variable
        /// Throws exception if the variable is not declared
        /// </summary>
        /// <param name="name">The name of the variable of the type integer to be worked on</param>
        /// <param name="value">The value which is added to the variable</param>
        private void variableAssignmentPlus(string name, int value)
        {
            if (variableIntHT.ContainsKey(name))
            {
                IDictionaryEnumerator myEnumerator = variableIntHT.GetEnumerator();

                while (myEnumerator.MoveNext())
                {
                    if (myEnumerator.Key.ToString() == name)
                    {
                        var temp = myEnumerator.Value as IntMappedValue;
                        temp.value += value;

                        variableIntHT.Remove(name);
                        variableIntHT.Add(name, temp);
                        return;
                    }
                }
            }
            else
            {
                throw new variableException("Variable (integer) " + name + " is not declared");
            }
        }

        /// <summary>
        /// Substracts the value of the variable to the parameter value and assigns it to the variable
        /// Throws exception if the variable is not declared
        /// </summary>
        /// <param name="name">The name of the variable of the type integer to be worked on</param>
        /// <param name="value">The value which is Substracted to the variable</param>
        private void variableAssignmentMinus(string name, int value)
        {
            if (variableIntHT.ContainsKey(name))
            {
                IDictionaryEnumerator myEnumerator = variableIntHT.GetEnumerator();

                while (myEnumerator.MoveNext())
                {
                    if (myEnumerator.Key.ToString() == name)
                    {
                        var temp = myEnumerator.Value as IntMappedValue;
                        temp.value -= value;

                        variableIntHT.Remove(name);
                        variableIntHT.Add(name, temp);
                        return;
                    }
                }
            }
            else
            {
                throw new variableException("Variable (integer) " + name + " is not declared");
            }
        }

        /// <summary>
        /// Adds one to the value of the variable
        /// Throws exception if the variable is not declared
        /// </summary>
        /// <param name="name">The name of the variable of the type integer to be worked on</param>
        private void variablePlusPlus(string name)
        {
            if (variableIntHT.ContainsKey(name))
            {
                IDictionaryEnumerator myEnumerator = variableIntHT.GetEnumerator();

                while (myEnumerator.MoveNext())
                {
                    if (myEnumerator.Key.ToString() == name)
                    {
                        var temp = myEnumerator.Value as IntMappedValue;
                        temp.value++;

                        variableIntHT.Remove(name);
                        variableIntHT.Add(name, temp);
                        return;
                    }
                }
            }
            else
            {
                throw new variableException("Variable (integer) " + name + " is not declared");
            }
        }

        /// <summary>
        /// Substracts one to the value of the variable
        /// Throws exception if the variable is not declared
        /// </summary>
        /// <param name="name">The name of the variable of the type integer to be worked on</param>
        private void variableMinusMinus(string name)
        {
            if (variableIntHT.ContainsKey(name))
            {
                IDictionaryEnumerator myEnumerator = variableIntHT.GetEnumerator();

                while (myEnumerator.MoveNext())
                {
                    if (myEnumerator.Key.ToString() == name)
                    {
                        var temp = myEnumerator.Value as IntMappedValue;
                        temp.value--;

                        variableIntHT.Remove(name);
                        variableIntHT.Add(name, temp);
                        return;
                    }
                }
            }
            else
            {
                throw new variableException("Variable (integer) " + name + " is not declared");
            }
        }

        /// <summary>
        /// Runs through the CommonTree recursively and calculates the result of the math expression
        /// </summary>
        /// <param name="tree">CommonTree containing a math expression</param>
        /// <returns>Returns the result of the math expression as an integer</returns>
        private int mathExpression(CommonTree tree)
        {
            int result = 0;
            int a;
            int b;
            try
            {
                if (tree.Children != null)
                {
                    if (tree.Text != CRLF)
                            {
                                //Switchstatement
                                switch (tree.Text)
                                {
                                    case "+":
                                        {
                                            if (tree.Children[0].ToString() == "+"
                                                || tree.Children[0].ToString() == "-"
                                                || tree.Children[0].ToString() == "*"
                                                || tree.Children[0].ToString() == "/")
                                            {
                                                a = mathExpression(tree.Children[0] as CommonTree);
                                            }
                                            else
                                            {
                                                a = childValueInt(tree.Children[0] as CommonTree);

                                            }


                                                b = childValueInt(tree.Children[1] as CommonTree);
                                            

                                            result = a + b;
                                               
                                            break;
                                        }
                                    case "-":
                                        {
                                            if (tree.Children[0].ToString() == "+"
                                                || tree.Children[0].ToString() == "-"
                                                || tree.Children[0].ToString() == "*"
                                                || tree.Children[0].ToString() == "/")
                                            {
                                                a = mathExpression(tree.Children[0] as CommonTree);
                                            }
                                            else
                                            {
                                                a = childValueInt(tree.Children[0] as CommonTree);

                                            }

                                                b = childValueInt(tree.Children[1] as CommonTree);
                                            

                                            result = a - b;

                                            break;
                                        }
                                    case "*":
                                        {
                                            if (tree.Children[0].ToString() == "+"
                                                || tree.Children[0].ToString() == "-"
                                                || tree.Children[0].ToString() == "*"
                                                || tree.Children[0].ToString() == "/")
                                            {
                                                a = mathExpression(tree.Children[0] as CommonTree);
                                            }
                                            else
                                            {
                                                a = childValueInt(tree.Children[0] as CommonTree);

                                            }


                                                b = childValueInt(tree.Children[1] as CommonTree);
                                            

                                            result = a * b;

                                            break;
                                        }
                                    case "/":
                                        {

                                            if (tree.Children[0].ToString() == "+"
                                                || tree.Children[0].ToString() == "-"
                                                || tree.Children[0].ToString() == "*"
                                                || tree.Children[0].ToString() == "/")
                                            {
                                                a = mathExpression(tree.Children[0] as CommonTree);
                                            }
                                            else
                                            {
                                                a = childValueInt(tree.Children[0] as CommonTree);

                                            }
                                            

                                                b = childValueInt(tree.Children[1] as CommonTree);
                                            

                                            if( a == 0 || b == 0)
                                            {
                                                throw new DivideByZeroException();
                                            }
                                            result = a / b;

                                            break;
                                        }
                                        default:
                                        {
                                            result = childValueInt(tree);
                                            break;
                                        }
                                }
                                
                            }
                        
                    }
                else
                {
                    result = childValueInt(tree);
                }
                
            }
            catch (NullReferenceException)
            {
            }
            catch(DivideByZeroException)
            {
            }

            return result;
        }

        /// <summary>
        /// This function returns the value of a Commmontree as an integer
        /// </summary>
        /// <param name="tree">CommonTree containing an integer value or a name of a variable of the type integer</param>
        /// <returns>Returns a integer value</returns>
        private int childValueInt(CommonTree tree)
        {
            int result;
            
            if (int.TryParse(tree.Text, out result)) { }
            else
            {
                if (variableIntHT.ContainsKey(tree.Text))
                {
                    IDictionaryEnumerator myEnumerator = variableIntHT.GetEnumerator();

                    while (myEnumerator.MoveNext())
                    {
                        if (myEnumerator.Key.ToString() == tree.Text)
                        {
                            var temp = myEnumerator.Value as IntMappedValue;
                            result = temp.value;
                        }
                    }
                }
                else
                {
                    throw new variableException("Variable " + tree.Text + " not declared");
                }
            }
            return result;
        }

        /// <summary>
        /// This function returns the value of a Commmontree as a list of integers
        /// </summary>
        /// <param name="tree">CommonTree containing 5 numbers or the name of a variable of the type vector</param>
        /// <returns>Return a list containing the 5 numbers as integer values or
        ///  the 5 integer values contained in the vector</returns>
        private List<int> childValueVector(CommonTree tree)
        {
            List<int> result = new List<int>();
            int value;

            if (int.TryParse(tree.Children[0].ToString(), out value))
            {
                result.Add(value);
                int.TryParse(tree.Children[1].ToString(), out value);
                result.Add(value);
                int.TryParse(tree.Children[2].ToString(), out value);
                result.Add(value);
                int.TryParse(tree.Children[3].ToString(), out value);
                result.Add(value);
                int.TryParse(tree.Children[4].ToString(), out value);
                result.Add(value);
            }
            else
            {
                if (variableVectorHT.ContainsKey(tree.Children[0].ToString()))
                {
                    IDictionaryEnumerator myEnumerator = variableVectorHT.GetEnumerator();

                    while (myEnumerator.MoveNext())
                    {
                        if (myEnumerator.Key.ToString() == tree.Children[0].ToString())
                        {
                            var temp = myEnumerator.Value as VectorMappedValue;
                            result = temp.value;
                        }
                    }
                }
                else
                {
                    throw new variableException("Variable (vector) " + tree.Children[0].ToString() + " not declared");
                }
            }
            return result;
        }
    }
}

